<template>
  <div class="update-photo">
    <img :src="img" class="img" ref="img" />

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { updateUserPhoto } from '@/api/user.js';

export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [Object, String],
      required: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  methods: {
    async updateUserPhoto(blob) {
      const formData = new FormData();
      formData.append('photo', blob);
      try {
        const { data } = await updateUserPhoto(formData);
        this.$toast.success('上传成功');
        this.$emit('close');
        this.$emit('update-photo', data.data.photo);
      } catch (err) {
        this.$toast.fail('上传失败');
      }
    },
    onConfirm() {
      this.$toast.loading({
        message: '上传中...',
        forbidClick: true, // 禁止背景点击
        duration: 0, // 持续展示
      });

      // console.log(this.cropper.getData()); // 给服务端的裁切数据
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        // 客户端获取裁切的文件对象
        this.updateUserPhoto(blob);
      });
    },
  },
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
};
</script>

<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
